package com.didispace;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.client.RestTemplate;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.schedulers.Schedulers;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;

/**
 * HystrixObservableCommand使用示例
 * 只需要集成HystrixObservableCommand类，并覆写construct方法即可
 * @author Administrator
 *
 */
public class UserHystrixObservableCommand extends HystrixObservableCommand<User> {

	private RestTemplate restTemplate;
	
	private String[] ids;// 模拟前端的批处理，例如需要删除id为1,2,3,4的记录

	public UserHystrixObservableCommand(String[] ids, RestTemplate restTemplate) {
		super(HystrixCommandGroupKey.Factory.asKey("usercommand"));// 调用父类构造方法
		this.ids = ids;
	}

	@Override
	protected Observable<User> construct() {
		System.out.println(Thread.currentThread().getName()+"is running......");
		return Observable.create(new OnSubscribe<User>() {
			/*
			 * Observable有三个关键的事件方法，分别为onNext，onCompleted，onError，意思很容易懂哈
			 */
			@Override
			public void call(Subscriber<? super User> observer) {
				try {// 写业务逻辑，注意try-catch
					if (!observer.isUnsubscribed()) {
						for (String id : ids) {
							User u = new User();
							u.setId(id);
//							TimeUnit.SECONDS.sleep(3);
							observer.onNext(u);
						}
						observer.onCompleted();
					}
				} catch (Exception e) {
					observer.onError(e);
				}
			}
		}).subscribeOn(Schedulers.io());
	}

	/**
	 * fallback方法的写法，覆写resumeWithFallback方法
	 * 当调用出现异常时，会调用该降级方法
	 */
	@Override
	public Observable<User> resumeWithFallback() {
		return Observable.create(new OnSubscribe<User>() {

			@Override
			public void call(Subscriber<? super User> observer) {
				try {
					if (!observer.isUnsubscribed()) {
						User u = new User();
						u.setUserName("刘先生");
						u.setId("1");
						observer.onNext(u);
						observer.onCompleted();
					}
				} catch (Exception e) {
					observer.onError(e);
				}
			}
		}).subscribeOn(Schedulers.io());
	}
}